package com.naml.d_methods;

/**
 * @author marin
 * @version 1.0
 * @date 2025/4/28 20:58
 * @desc 演示线程的礼让--但是不一定礼让成功。看cpu的调度分配的时间片段。
 */
@SuppressWarnings("all")
public class ThreadYield04 {
    public static void main(String[] args) throws InterruptedException {
        ThreadYield yield = new ThreadYield();
        yield.start();

        for (int i = 1; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ": 跑了" + i + "米...");
            Thread.sleep(1000);
            if (i % 10 == 5) {
                System.out.println(Thread.currentThread().getName() + "准备礼让" + yield.getName() +"先跑...");
                Thread.yield();
            }
        }
    }
}

class ThreadYield extends Thread {
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            try {
                System.err.println(Thread.currentThread().getName() + ": 跑了" + i +"米...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}